import React, { useState, useEffect } from 'react';
import { Select, Form, Checkbox, Modal, DatePicker, message } from 'antd';
import moment from 'moment';
import { getProfileList, activityDetailExportV2 } from '@/services/operate';

let timeout: null;
// @ts-ignore
let currentValue: string;

type Props = {
  modelVisible: boolean;
};

const { RangePicker } = DatePicker;

const ModelOutput: React.FC<Props> = ({ modelVisible }) => {
  const [dataOption, setDataOption] = useState([]);
  const [modelNumVisible, setModelNumVisible] = useState(false);
  const [confirmLoad, setConfirmLoad] = useState(false);
  const [modalNumForm] = Form.useForm();
  const [selectedStartDate, setSelectedStartDate] = useState(null);

  const handleNumCancel = () => {
    setModelNumVisible(false);
    modalNumForm.resetFields();
  };

  // 校验时间段是否超过一个月
  const isWithinOneMonth = (time1: string, time2: string) => {
    const start = moment(time1);
    const end = moment(time2);

    // 确保 start 在 end 之前
    if (start.isAfter(end)) {
      return false;
    }

    // 计算时间差
    const duration = moment.duration(end.diff(start));
    return duration.asMonths() <= 1;
  };

  const handleNumOK = () => {
    modalNumForm.validateFields().then(async (values) => {
      console.log('values==', values);
      const param: any = {
        activityIds: values.activityIds,
        channelIds: values.channelIds,
        startDate:
          values.rangeDate && values.rangeDate[0]
            ? moment(values.rangeDate[0]).format('YYYY-MM-DD')
            : '',
        endDate:
          values.rangeDate && values.rangeDate[1]
            ? moment(values.rangeDate[1]).format('YYYY-MM-DD')
            : '',
      };
      if (!param.startDate || !param.endDate) {
        message.error('时间范围不得为空');
        return;
      }
      if (param.activityIds && param.activityIds.length > 500) {
        message.error('最多只能选择500个活动');
        return;
      }
      if (!isWithinOneMonth(param.startDate, param.endDate)) {
        message.error('时间区间不超过1个月');
        return;
      }

      try {
        setConfirmLoad(true);
        const resUpdate = await activityDetailExportV2(param);
        setConfirmLoad(false);
        const url = window.URL.createObjectURL(resUpdate.data);
        const link = document.createElement('a');
        link.style.display = 'none';
        const Disposition = resUpdate?.Disposition || '';
        if (!Disposition) {
          message.error('暂无数据');
          return;
        }
        link.download = decodeURIComponent(Disposition?.split(`filename=`)[1]) || '导出列表'; // 下载的文件名称
        // decodeURIComponent(Disposition?.split(`filename*=utf-8''`)[1]) || '导出列表'; // 下载的文件名称
        // filename=
        link.href = url;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
        message.success('导出成功');
      } catch (error) {
        message.error('导出失败');
      }
      return;
    });
  };

  // 拉下option请求接口--防抖
  const fetch = (value: string, callback: Function) => {
    if (timeout) {
      clearTimeout(timeout);
      timeout = null;
    }
    currentValue = value;
    const fake = async () => {
      const { code, data } = await getProfileList({
        activityId: value || '',
        profileStatus: 'ALL', // 已提交
      });
      if (code === 200 && data) {
        const dataBro = data.map((item: any) => item.activityId) || [];
        callback(dataBro);
      }
    };
    // @ts-ignore
    timeout = setTimeout(fake, 300);
  };

  // 下拉框输入时 掉接口
  const handleSearch = (newValue: string) => {
    fetch(newValue, setDataOption);
  };

  useEffect(() => {
    if (modelVisible) {
      setModelNumVisible(true);
      handleSearch('');
    }
  }, [modelVisible]);

  // // 禁用不符合条件的日期
  // const disabledDate = (current: any) => {
  //   if (!selectedStartDate) {
  //     return false; // 如果没有选择开始日期，则不禁用任何日期
  //   }
  //   // 禁用早于开始日期和超过1个月后的日期
  //   const endDateLimit = selectedStartDate?.clone().add(1, 'month');
  //   return current && (current < selectedStartDate || current > endDateLimit);
  // };

  return (
    <Modal
      title="活动导出"
      width={520}
      open={modelNumVisible}
      onOk={handleNumOK}
      onCancel={handleNumCancel}
      confirmLoading={confirmLoad}
    >
      <Form
        labelCol={{ span: 6 }}
        form={modalNumForm}
        initialValues={{
          rangeDate: [null, null],
          activityIds: [],
          channelIds: ['CPOS'],
        }}
      >
        <Form.Item
          label="时间范围"
          name="rangeDate"
          style={{ width: 400 }}
          rules={[{ required: true, message: '不得为空' }]}
        >
          <RangePicker
            style={{ width: 300 }}
            format="YYYY-MM-DD"
            // disabledDate={disabledDate}
            // onChange={(dates) => {
            //   if (dates && dates[0]) {
            //     setSelectedStartDate(dates[0]);
            //   }
            // }}
          />
        </Form.Item>
        <Form.Item
          label="活动定义"
          name="activityIds"
          style={{ width: 400 }}
          rules={[{ required: true, message: '不得为空' }]}
        >
          <Select
            mode="multiple"
            showSearch
            placeholder={'请选择'}
            defaultActiveFirstOption={false}
            showArrow={true}
            filterOption={false}
            onSearch={handleSearch}
            // onChange={handleChange}
            notFoundContent={null}
            options={(dataOption || [])?.map((d: any) => ({
              value: d,
              label: d,
            }))}
            maxTagCount={'responsive'}
          />
        </Form.Item>

        <Form.Item
          label="渠道"
          name="channelIds"
          style={{ width: 400 }}
          rules={[{ required: true, message: '不得为空' }]}
        >
          <Checkbox.Group
            options={[
              { label: '堂食', value: 'CPOS' },
              { label: '外送', value: 'Delivery' },
            ]}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default ModelOutput;
